package com.api.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.api.common.exception.MySystemException;
import com.api.common.page.PageData;
import com.api.common.service.impl.BaseServiceImpl;
import com.api.entity.Item;
import com.api.entity.Token;
import com.api.entity.User;
import com.api.entity.dto.ItemDTO;
import com.api.entity.dto.LoginDTO;
import com.api.entity.dto.UserDTO;
import com.api.mapper.UserMapper;
import com.api.service.TokenService;
import com.api.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-08-10
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private  TokenService tokenService;
    @Autowired
    private  UserMapper userMapper;


    @Override
    public PageData<UserDTO> page(Map<String, Object> params) {
        IPage<User> page = baseDao.selectPage(getPage(params,  false),
                getWrapper(params)
        );
        return getPageData(page, UserDTO.class);
    }
    private QueryWrapper<User> getWrapper(Map<String, Object> params) {
        String nickName = (String) params.get("nickName");
        String userName = (String) params.get("userName");
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(nickName), "nick_name", nickName);
        wrapper.like(StrUtil.isNotBlank(userName), "user_name", userName);
        return wrapper;
    }



    @Override
    public User getUserByUserId(Long userId) {


        return userMapper.selectById(userId);
    }
    @Override
    public Map<String, Object> login(LoginDTO dto) {
        LambdaQueryWrapper<User> userLwq = new LambdaQueryWrapper<>();
        userLwq.eq(User::getUserName,dto.getUsername());
        User user = userMapper.selectOne(userLwq);
        if (user == null) {
            throw  new MySystemException("账号不存在");
        }

        //密码错误
        if (!user.getPassword().equals(DigestUtil.sha256Hex(dto.getPassword()))) {
            throw new MySystemException("密码错误");
        }

        //获取登录token
        Token tokenEntity = tokenService.createToken(user.getId());
        Map<String, Object> map = new HashMap<>(2);
        map.put("token", tokenEntity.getToken());
        map.put("expire", tokenEntity.getExpireDate().getTime() - System.currentTimeMillis());
        return map;
    }

}
